import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { canTurnTo } from '@/utils'
import getPageTitle from '@/utils/get-page-title'
import routes from '@/router/routers'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        if (!store.state.user.hasRule) {
          store.dispatch('user/getInfo').then(user => {
            user.access = store.state.user.access
            if (canTurnTo(to.name, user.access, routes)) next()
            else next({ replace: true, name: 'error_404' })
          })
        } else {
          if (canTurnTo(to.name, store.state.user.access, routes)) next()
          // 有权限，可访问
          else next({ replace: true, name: 'error_404' }) // 无权限，重定向到404页面
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
